<template>
  <div class="rolesBox">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/roles' }">权限管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/roles' }">角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row type="flex">
        <el-col :span="24">
          <el-button type="primary" @click="FormVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <el-table :data="tableData" border style="width: 100%  margin-top:10px">
        <el-table-column type="expand" width="50">
          <template slot-scope="props">
            <!-- <span>{{ props.row }}</span> -->
            <el-row v-for="(first, i) in props.row.children" :key="i">
              <el-col :span="4">
                <el-tag
                  closable
                  effect="dark"
                  @close="handleClose(first, props.row)"
                  >{{ first.authName }}</el-tag
                >
                <i class="el-icon-caret-right" v-if="first.children"></i>
              </el-col>

              <el-col :span="20">
                <el-row v-for="(second, j) in first.children" :key="j">
                  <el-col :span="6">
                    <el-tag
                      closable
                      effect="dark"
                      type="success"
                      @close="handleClose(second, props.row)"
                      >{{ second.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right" v-if="second.children"></i>
                  </el-col>

                  <el-col :span="18">
                    <el-tag
                      closable
                      type="warning"
                      effect="dark"
                      v-for="(three, j) in second.children"
                      :key="j"
                      @close="handleClose(three, props.row)"
                      >{{ three.authName }}

                      <i class="el-icon-caret-right" v-if="three.children"></i>
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>

        <el-table-column prop="id" label="#" width="100" align="center">
        </el-table-column>

        <el-table-column prop="roleName" label="角色名称" align="center">
        </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述" align="center">
        </el-table-column>
        <!-- "id": 30,
            "roleName": "主管",
            "roleDesc": "技术负责人",   
     -->
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >

            <el-button
              size="mini"
              type="warning"
              @click="allocatedLimits(scope.$index, scope.row)"
              >角色授权</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!--  角色授权弹框 -->
    <el-dialog title="授权角色" :visible.sync="dialogFormVisible">
      <div class="tree-container">
        <el-tree
          default-expand-all
          :data="rightsData"
          show-checkbox
          node-key="id"
          :default-expanded-keys="[2, 3]"
          :default-checked-keys="[5]"
          :props="defaultProps"
        >
        </el-tree>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary">确 定</el-button>
      </div>
    </el-dialog>
    <!--  添加用户弹框 -->
    <el-dialog title="添加角色" :visible.sync="FormVisible">
      <el-form :model="form" ref="form" :rules="rules">
        <el-form-item
          label="角色名称"
          prop="roleName"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="角色描述"
          prop="roleDesc"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="FormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </div>
    </el-dialog>
    <!--  编辑用户弹框 -->
    <el-dialog title="编辑角色" :visible.sync="editeDialogFormVisible">
      <el-form :model="editeForm" ref="form" :rules="rules">
        <el-form-item
          label="角色名称"
          prop="roleName"
          :label-width="formLabelWidth"
        >
          <el-input v-model="editeForm.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="角色描述"
          prop="roleDesc"
          :label-width="formLabelWidth"
        >
          <el-input v-model="editeForm.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="editeDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确定</el-button>
      </div>
    </el-dialog>
    <!--  角色授权弹框 -->
    <el-dialog title="授权角色" :visible.sync="empowerDialogFormVisible">
      <div class="tree-container">
        <!-- :default-expanded-keys="[2, 3]" -->
        <el-tree
          ref="tree"
          highlight-current
          default-expand-all
          :data="rightsData"
          show-checkbox
          node-key="id"
          :default-checked-keys="selectedRights"
          :props="defaultProps"
          @check-change="selectCheckEvent"
        >
        </el-tree>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="empowerDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEmpower">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getRoles,
  getDeleteRolesRights,
  getRolesRights,
  getRights,
  getRolesDelete,
  getAddRoles,
  getEditRoles,
  getQueryRolesById,
} from "../../api/index";
export default {
  data() {
    return {
      // role_id: 0,// 定义角色id
      tableData: [],
      dialogFormVisible: false, // 初始弹框状态
      rightsData: [],
      expandedKeys: [],
      checkedKeys: [],
      defaultProps: {
        children: "children",
        label: "authName",
      },
      // 定义弹框数据
      FormVisible: false,
      form: {
        username: "",
        password: "",
      },
      formLabelWidth: "200px",
      //验证规则
      rules: {
        roleName: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
        ],

        roleDesc: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
        ],
      },
      //编辑用户数据定义
      editeDialogFormVisible: false,
      editeForm: {
        // roleId:"",
        roleName: "",
        roleDesc: "",
      },
      //授权弹框
      empowerDialogFormVisible: false,
      selectedRights: [], // 初始化选中的角色授权
      roleId: "", //  定义 角色id
      rids: "", //   定义 权限 ID 列表（字符串
    };
  },
  methods: {
    async initGetRoles() {
      let {
        data,
        meta: { status },
      } = await getRoles();
      if (status != 200) return this.$message.error("请求失败");
      this.tableData = data;
    },
    //删除用户
    async handleDelete(index, item) {
      // console.log(index,item);
      let res = await this.$confirm("此操作将永久删除该用户, 是否继续?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch(() => {}); // 这里的取消必须加上一个catch 的回调函数
      if (res != "confirm") return this.$message.info("取消删除");
      let {
        meta: { status, msg },
      } = await getRolesDelete({ id: item.id });
      if (status == 200) {
        this.$message.success("删除成功");
        this.initGetRoles();
      } else {
        this.$message.error("删除失败");
      }
    },
    //添加用户逻辑
    async addRoles() {
      //   1 表单的验证
      //   2 验证通过后 发送请求
      //   3 发送请求成功后关闭弹框  重新刷新页面

      //  1 表单的验证
      let success = await this.$refs["form"].validate().catch(() => {});
      // console.log(success);

      if (!success) return false;
      // 2 验证通过后 发送请求
      let {
        meta: { status },
      } = await getAddRoles(this.form);

      if (status == 201) {
        this.$message.success("添加用户成功");
        //关闭弹框
        this.FormVisible = false;
        // 重新刷新页面
        this.initGetRoles();
      }
    },
    //编辑
    async handleEdit(index, item) {
      let res = await getQueryRolesById({ id: item.id });
      let {
        data,
        meta: { status },
      } = res;
      if (status != 200) return this.$message.info("查询失败了");
      this.editeForm = data;
      // console.log(data);
      this.editeDialogFormVisible = true;
    },
    async editRoles() {
      let {
        meta: { status },
      } = await getEditRoles(this.editeForm);
      if (status != 200) return this.$message.info("编辑失败了");
      this.editeDialogFormVisible = false;
      this.initGetRoles();
    },
    // 点击关闭tag 事件
    // async handleClose(tag, id) {
    //   let {
    //     data,
    //     meta: { status },
    //   } = await getDeleteRolesRights({ roleId: id, rightId: tag.id });
    //   if (status != 200) return this.$message.error("删除授权失败");
    // console.log(data); //返回的数据 是我们删除后的数据
    // this.$message.success("删除授权成功")
    // this.tableData.forEach(item=>{
    //     if(item.id==id) {
    //         console.log('1');
    //         item.children=data
    //     }
    // })
    // },
    //优化
    async handleClose(tag, scopedRow) {
      let isFalg = await this.$confirm(
        "此操作将永久删除该权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch(() => {});
      if (!isFalg) return this.$message.info({ message: "已取消删除" });
      // console.log(tag);
      // console.log(scopedRow);
      let {
        data,
        meta: { status },
      } = await getDeleteRolesRights({ roleId: scopedRow.id, rightId: tag.id });
      if (status != 200) return this.$message.error("删除授权失败");
      // console.log(data); //返回的数据 是我们删除后的数据
      this.$message.success("删除授权权限成功");
      scopedRow.children = data; //  返回的值 重新更新当前这一项的children
    },
    // 角色授权
    async allocatedLimits(i, scopedRow) {
      //每次打开弹框的时候 清除之前已经的授权id(第三级id)
      this.selectedRights = [];
      //  console.log(   scopedRow.id);
      this.roleId = scopedRow.id; //获取角色id
      //  debugger;
      //1 弹框打开
      this.empowerDialogFormVisible = true;
      //2 数据展示
      let {
        data,
        meta: { status },
      } = await getRights({ type: "tree" });
      if (status != 200) return this.$message.error("请求失败");

      this.rightsData = data;
      //3  勾选状态展示
      // 3.1  获取到当前的用户
      // console.log(scopedRow);
      this.checkNodeId(scopedRow, this.selectedRights);
    },
    // 采用递归去获取最后一层被选中的授权id
    // scopedRowNode  表示节点对象
    // selectedRightsArr  表示需要存储id 的空数组
    checkNodeId(scopedRowNode, selectedRightsArr) {
      if (!scopedRowNode.children) {
        //如果没有children  表示是最后一个节点
        return selectedRightsArr.push(scopedRowNode.id);
      }
      // 表示一定有children
      scopedRowNode.children.forEach((item) => {
        return this.checkNodeId(item, selectedRightsArr);
      });
    },
    // 点击确定 提交 授权逻辑功能
    async submitEmpower() {
      //1 获取到所有 选中已经 半选中的授权 id
      //2  | 参数名  | 参数说明
      // roleId ( 角色 ID)
      // rids   (权限 ID 列表（字符串）)
      let {
        meta: { msg, status },
      } = await getRolesRights({ roleId: this.roleId, rids: this.rids });
      //  console.log(msg);
      //  alert(msg)
      if (status != 200) return this.$message.error("授权权限失败");
      // 成功了后 1  关闭弹框  2  刷新页面
      this.empowerDialogFormVisible = false;
      this.initGetRoles();
    },
    //  获取选中节点的状态
    selectCheckEvent() {
      let checkedKeys = this.$refs.tree.getCheckedKeys(); // 全选中
      let halfCheckedKeys = this.$refs.tree.getHalfCheckedKeys(); // 半选中
      let arr = [...checkedKeys, ...halfCheckedKeys];
      // console.log(arr);
      this.rids = arr.join();
    },
  },

  created() {
    this.initGetRoles();
  },
};
</script>

<style scoped>
.box-card {
  width: 1200px;
}
.rolesBox {
  padding-left: 20px;
  margin-top: 20px;
  overflow: auto;
}

.el-table {
  margin-top: 20px;
}

.el-pagination {
  margin: 20px auto;
  text-align: center;
}

.el-row {
  padding-left: 20px;
}

.el-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}
</style>
